<template>
  <div class="container">
    <el-row>
      <el-col :span="14" :offset="6">
        <el-form
          :model="ruleForm"
          ref="ruleForm"
          :rules="rules"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="客户名称:" required prop="partyName">
            <el-input v-model="ruleForm.partyName"></el-input>
          </el-form-item>
          <el-form-item label="证件类型:" required prop="certType">
            <el-select
              v-model="ruleForm.certType"
              placeholder="请选择证件类型"
              size="medium"
              @change="addcertTypeChange"
            >
              <el-option
                v-for="item in idCardList"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="证件号码:"
            placeholder="请输入内容"
            prop="certNum"
            :required="
              ruleForm.certType == '7' || ruleForm.certType == '72'
                ? false
                : true
            "
          >
            <el-input v-model="ruleForm.certNum"></el-input>
          </el-form-item>
          <el-form-item
            label="审核人:"
            :prop="user.orgId != '1944640' ? 'auditName':''"
            :required="isAuditIdShow"
            v-show="isAuditIdShow"
          >
            <dic-customer-select
              :value="ruleForm.auditName"
              title="审核人"
              ref="auditIdRef"
              size="50%"
              @inLoadAjax="auditIdAjaxHandel"
            >
              <!-- 表单 -->
              <el-form
                :inline="false"
                label-width="100px"
                :model="addauditIdForm"
                ref="auditIdFormRef"
              >
                <el-row :gutter="10">
                  <el-col :span="10">
                    <div class="grid-content bg-purple">
                      <el-form-item label="员工编码" class="u-ipt">
                        <el-input
                          placeholder=""
                          v-model="addauditIdForm.staffCode"
                          class="input-with-select"
                        >
                        </el-input>
                      </el-form-item>
                    </div>
                  </el-col>
                  <el-col :span="10">
                    <div class="grid-content bg-purple">
                      <el-form-item label="员工姓名" class="u-ipt">
                        <el-input
                          placeholder="请输入内容"
                          v-model="addauditIdForm.staffName"
                          class="input-with-select"
                        >
                        </el-input>
                      </el-form-item>
                    </div>
                  </el-col>
                  <el-col :span="4">
                    <el-button type="primary" size="small" @click="auditIdQuery"
                      >查询</el-button
                    >
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="审核人姓名:">
                      <span style="position: relative; bottom: 1px">
                        {{ addauditIdForm.staffNameChoose }}
                      </span>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
              <DicTable
                ref="commonRegionTable"
                stripe
                highlight-current-row
                :columnData="auditIdColumns"
                :tableData="auditIdTableData"
                :loading="auditIdTableLoading"
                :currentPage="auditIdTablePage.pageIndex"
                :pageSize="auditIdTablePage.pageSize"
                :totalResult="auditIdTablePage.rowCount"
                :pager="true"
                @current-change="auditIdCurrentChangeEvent"
                @on-page-change="auditIdHandlePageChange"
              >
              </DicTable>
              <div class="text-c">
                <el-button
                  type="primary"
                  size="small"
                  @click="sunmitAuditIdHandel"
                  >确定</el-button
                >
              </div>
            </dic-customer-select>
          </el-form-item>
          <el-form-item label="营销责任地:" prop="regionName">
            <el-input v-model="ruleForm.regionName" disabled></el-input>
          </el-form-item>
          <el-form-item
            label="证件照片:"
            :required="
              ruleForm.certType == '7' || ruleForm.certType == '72'
                ? true
                : false
            "
          >
            <el-upload
              :action="uploadUrl"
              list-type="picture-card"
              :show-file-list="true"
              :file-list="custAddList"
              :data="custAddData"
              :multiple="false"
              accept=".jpg,.jpeg,.png,.JPG,.JPEG"
              :on-change="custAddChange"
              :on-preview="custAddPreview"
              :on-success="custAddSuccess"
              :before-upload="custAddUpload"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="custAddDialogVisible" append-to-body>
              <img width="100%" :src="custAddDialogImageUrl" alt="" />
            </el-dialog>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row style="text-align: center">
      <el-button type="primary" @click="nextStepHandel" class="btnStyle"
        >下一步</el-button
      >
      <el-button @click="returnPreStep()" class="btnStyle">返回</el-button>
    </el-row>
    <dic-dialog
      title="提示"
      :visible.sync="onComplianceVisible"
      width="70%"
      :close-on-click-modal="false"
      append-to-body
    >
      <span>
        <el-alert
          :title="alertTitle"
          type="warning"
          :closable="false"
          class="mb20"
        >
        </el-alert>

        <DicTable
          stripe
          :columnData="nonComplianceviewTableColumns"
          :tableData="nonComplianceviewTableData"
        >
          <template #opt="{ row }">
            <el-button type="primary" @click="changeRow(row)">选择</el-button>
          </template>
        </DicTable>
        <el-alert
          v-if="titleMsgIsshow"
          :title="titleMsg"
          type="warning"
          :closable="false"
          class="mt20"
        >
        </el-alert>
      </span>

      <span slot="footer" class="dialog-footer">
        <el-button @click="onComplianceVisible = false">关闭</el-button>
      </span>
    </dic-dialog>
  </div>
</template>

<script>
import ABCustManage from "@/api/customer/ABCustManage";
import DicTable from "@/components/public/DicTable";
import DicDialog from "@/components/dicppm-ui/DicDialog";
import DicCustomerSelect from "@/components/customer/form/DicCustomerSelect";
import { mapState } from "vuex";
import validRules from "@/views/customer/valide/gaoyjValidRules.js";
export default {
  data() {
    return {
      ruleForm: {
        partyName: "", //客户名称
        certType: "", //证件类型
        certNum: "", //证件号码
        regionName: "", //营销责任地名称
        regionNbr: "", //营销责任地编码
        auditId: "", //审核人id
        audit: "",
        auditName: "", //审核人名称
        photoName: "", //证件名称
        photoPath: "", //证件路径
        staffId: "",
        commonRegionId: "",
        certAddr: "", //查询省客户返回地址
      },
      rules: {
        partyName: [
          { required: true, message: "请输入客户名称", trigger: "blur" },
        ],

        certType: [
          {
            required: true,
            validator: validRules.gaoyj_checkIdCardSType,
            message: "请选择证件类型",
            trigger: "change",
          },
        ],

        certNum: [
          {
            validator: validRules.gaoyj_checkIdCardNum,
            trigger: "blur",
          },
        ],
        auditName:[
          { validator: validRules.gaoyj_checkAuditName, trigger: "blur",},
        ],
        regionName: [
          { required: true, message: "请填写营销责任地", trigger: "blur" },
        ],
      },
      idCardList: [], //证件类型列表
      imageUrl: "", //上传的图片
      //新建客户证件照片列表
      custAddList: [],
      //新建客户-上传证件照片
      uploadUrl: `${process.env.VUE_APP_CTX_CUST}/saveCustFile`,
      //新建客户-上传证件照片下后台传递的数据
      custAddData: {
        fileFlag: "partyNew",
        oldPhotoPath: "",
      },
      custAddDialogVisible: false,
      custAddDialogImageUrl: "",
      titleMsgIsshow: false,
      onComplianceVisible: false,
      alertTitle: "",
      titleMsg: "",
      nonComplianceviewTableColumns: [
        { field: "jtCustName", title: "客户名称" },
        {
          field: "orgUscc",
          title: "统一社会信用代码",
          width: 200,
          showOverflow: true,
        },
        { field: "certNum", title: "组织机构代码" },
        { field: "registerAddr", title: "注册地址", width: 400 },
        { slotName: "opt", title: "操作" },
      ],
      // 合规性不通过的逻辑列表
      nonComplianceviewTableData: [],
      // 审核人是否显示
      isAuditIdShow: false,
      addauditIdForm: {
        staffCode: "", //审核人编码
        staffName: "", //审核人名称
        staffNameChoose: "",
        staffCodeId: "", //选择审核人编码存放变量
      },
      auditIdColumns: [
        {
          field: "STAFF_CODE",
          title: "员工编码",
          fixed: "left",
          showOverflow: true,
          width: 100,
        },
        {
          field: "STAFF_NAME",
          title: "员工姓名",
          width: 200,
          fixed: "left",
          showOverflow: true,
        },
        { field: "MOBILE_PHONE", title: "员工联系方式", width: 200 },
        { field: "ORG_NAME", title: "组织名称", width: 200 },
        { field: "DEPARTMENT_NAME", title: "部门名称", width: 200 },
      ],
      auditIdTableData: [],
      auditIdTableLoading: false,
      auditIdTablePage: {
        pageIndex: 1,
        pageSize: 5,
        rowCount: 0,
        pageCount: 0,
      },
    };
  },

  components: {
    DicTable,
    DicDialog,
    DicCustomerSelect,
  },

  computed: {
    ...mapState("user", ["user"]),
  },

  mounted() {
    this.ruleForm.partyName = this.$route.query.custName;
    this.initValueIdType();
    this.initParty();
  },

  methods: {
    //初始化证件类型下拉框
    async initValueIdType() {
      const response = await ABCustManage.initValue({
        flag: "cert_type",
      });
      if (response.code == 200) {
        this.idCardList = response.meta.customers;
      }
    },
    //初始化接口
    async initParty() {
      var params = {
        commonRegionId: this.user.regionId,
        regionType: this.user.regionType,
        orgId: this.user.orgId,
        staffId: this.user.staffId,
      };
      let res = await ABCustManage.initParty(params);
      if (res.code == 200) {
        
        this.ruleForm.commonRegionId = res.meta.commonRegionId;
        this.ruleForm.regionName = res.meta.regionName;
        this.ruleForm.regionNbr = res.meta.regionNbr;
        this.rolesCount = res.meta.rolesCount;

        if (this.rolesCount == 0) {
          for (var i = 0; i < this.idCardList.length; i++) {
            if (this.idCardList[i] === "72") {
              this.idCardList.splice(i, 1);
            }
          }
        }
      }
    },
    //上传成功后触发事件
    custAddSuccess(res, file) {
      this.ruleForm.photoName = file.name;
      this.ruleForm.photoPath = res.meta.photoPath;
      this.custAddData.oldPhotoPath = res.meta.photoPath;
      if (res.code == 200) {
        this.$notify({
          title: "成功",
          message: "图片上传成功",
          type: "success",
        });
        this.$refs.ruleForm.clearValidate("photoName");
      }
    },
    custAddUpload(file) {
      const isPicType =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/jpg" ||
        file.type === "image/JPG" ||
        file.type === "image/JPEG";
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isPicType) {
        this.$message.error("上传头像图片只能是 JPG或者Png 格式!");
      }
      if (!isLt10M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isPicType && isLt10M;
    },
    custAddPreview(file) {
      this.custAddDialogImageUrl = file.url;
      this.custAddDialogVisible = true;
    },
    custAddChange(file, fileList) {
      var returnArr;
      if (fileList.length > 1) {
        returnArr == fileList.shift();
      }
      this.custAddList = fileList;
    },
    //证件类型切换
    addcertTypeChange(val) {
      this.$refs.ruleForm.clearValidate();
      // this.$refs.ruleForm.clearValidate("certNum");
      // this.$refs.ruleForm.clearValidate("photoPath");
      // this.$refs.ruleForm.clearValidate("photoName");
      if (val == "7" && this.user.orgId != "1944640") {
        this.isAuditIdShow = true;
      } else {
        this.isAuditIdShow = false;
        this.ruleForm.auditName = "";
        this.ruleForm.auditId = "";
      }
    },
    // 新建客户
    changeRow(row) {
      this.ruleForm.partyName = row.jtCustName;
      this.isAuditIdShow = false;
      this.ruleForm.auditName = "";
      this.ruleForm.auditId = "";
      if (row.orgUscc) {
        this.ruleForm.certNum = row.orgUscc;
        // 赋值证件类型
        this.ruleForm.certType = "49";
      } else {
        this.ruleForm.certNum = row.certNum;
        this.ruleForm.certType = "15";
      }
      this.onComplianceVisible = false;
    },
    //新建客户-审核人点击方法
    auditIdAjaxHandel(row) {
      this.auditIdTablePage.pageIndex = 1;
      this.auditIdTablePage.pageSize = 5;
      this.auditIdAjax();
    },
    subitForm() {
      this.isShow = false;
      this.$router.push("/custbaseinf");
    },
    // 审核人的ajax-初始化
    async auditIdAjax() {
      let params = {
        staffId: this.user.staffId,
        pageIndex: this.auditIdTablePage.pageIndex,
        pageSize: this.auditIdTablePage.pageSize,
        staffCode: this.addauditIdForm.staffCode,
        staffName: this.addauditIdForm.staffName,
      };
      let res = await ABCustManage.getAuditorList(params);
      if (res.code == 200) {
        this.auditIdTableData = res.meta.customers || [];
        this.auditIdTablePage.rowCount = Number(res.meta.pageInfo.rowCount);
        this.auditIdTablePage.pageCount = Number(res.meta.pageInfo.pageCount);
      } else {
        this.$notify.error({
          title: "错误",
          message: response.msg,
        });
      }
    },

    // 新建客户-证件类型切换党政军-显示的审核人弹窗-点击行
    auditIdCurrentChangeEvent(val) {
      
      
      this.addauditIdForm.staffNameChoose = val.data[val.$rowIndex].STAFF_NAME;
      this.addauditIdForm.staffCodeId = val.data[val.$rowIndex].STAFF_ID;
    },
    // 新建客户-证件类型切换党政军-显示的审核人弹窗-分页
    auditIdHandlePageChange(val) {
      this.auditIdTablePage.pageIndex = val.currentPage;
      this.auditIdTablePage.pageSize = val.pageSize;
      this.auditIdAjax();
    },
    // 点击审核人弹窗-确定将审核人的id带过来
    sunmitAuditIdHandel() {
      this.ruleForm.auditId = this.addauditIdForm.staffCodeId;
      this.ruleForm.auditName = this.addauditIdForm.staffNameChoose;
      this.$refs.auditIdRef.drawer = false;
    },
    // 审核人查询方法
    auditIdQuery() {
      this.auditIdTablePage.pageIndex = 1;
      this.auditIdTablePage.pageSize = 5;
      this.auditIdAjax();
    },
    //  新建客户点击下一步ajax交互
    nextStepHandel() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.nextStep();
        } else {
          return false;
        }
      });
    },
    //下一步按钮
    async nextStep() {
      if(this.ruleForm.photoPath == "" && this.isAuditIdShow){
        this.$alert('证件照片:不能为空!','提示',{type:'warning'})
        return
      }
      let params = {
        partyName: this.ruleForm.partyName,
        certType: this.ruleForm.certType,
        certNum: this.ruleForm.certNum,
        staffId: this.user.staffId,
        staffName: this.user.staffName,
        photoName: this.ruleForm.photoName,
        photoPath: this.ruleForm.photoPath,
        partyId: this.$route.query.partyId,
      };
      let result = await ABCustManage.saveCustAbPerfect(params);
      var res = result.meta;
      if (result.code == 200) {
        if (res.step == "2") {
          this.onComplianceVisible = true;
          if (res.ruleCode == "10002") {
            this.alertTitle =
              "合规性验证不通过：组代无数据，请确认是否以下疑似客户:";
            this.titleMsg = "如非以上疑似客户请上传证件照片";
            this.titleMsgIsshow = true;
          } else if (
            res.ruleCode == "10003" ||
            res.ruleCode == "10004" ||
            res.ruleCode == "10005"
          ) {
            this.alertTitle =
              "合规性验证不通过：客户名称不一致，正确客户信息如下：";
            this.titleMsg = "";
            this.titleMsgIsshow = false;
          } else if (res.ruleCode == "10010" || res.ruleCode == "10011") {
            this.alertTitle =
              "合规性验证不通过：证件号码不一致，正确客户信息如下：";
            this.titleMsg = "";
            this.titleMsgIsshow = false;
          } else {
            this.onComplianceVisible = false;
            this.$confirm(res.ruleMsg, "提示", {
              confirmButtonText: "关闭",
              showCancelButton: false,
              type: "warning",
              center: true,
            });
          }
          this.nonComplianceviewTableData = result.meta.suspectedCust;
        } else {
          if (res.resultCode == 0) {
            this.$router.push({
              path: "/custProvided",
              query: {
                partyId: this.$route.query.partyId,
                staffId: this.user.staffId,
                custId: this.$route.query.custId,
                partyNbr: res.partyNbr,
                custflag: this.ruleForm.auditId,
                commonRegionId: this.ruleForm.commonRegionId,
                regionName: this.ruleForm.regionName,
              },
            });
          } else {
            this.$message({
              showClose: true,
              message: result.meta.resultMsg,
              type: "error",
            });
          }
        }
      }
    },
    //返回按钮
    returnPreStep() {
      this.$router.push({
        path: "/abCustManage",
        query: {},
      });
    },
    //图片显示
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      
    },
  },
};
</script>
<style lang='scss' scoped>
.container {
  height: 100%;
  width: 100%;
  background-color: #fff;
  padding: 50px 15px 0;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.el-icon-plus {
  border: 1px dashed #d9d9d9;
}
.el-upload__tip {
  color: red;
}
.el-form-item {
  margin-bottom: 0.2rem;
}
.btnStyle {
  width: 80px;
}
.text-c {
  text-align: center;
}
</style>